<?php
namespace app\manage\controller;
use think\Controller;
use think\Db;
use app\manage\model\Manage as ManageModel;
use think\Session;
use think\Loader;

class Login extends Controller
{
  public function index(){

    return view();
  }

  public function doLogin(){
    if(request()->isPost()){
      $data = input('post.');

      //登录后台验证
      $validate = Loader::validate('Login');

      if(!$validate->check($data)){
          $this->error($validate->getError());
          die;
      }
      $this->check_verify($data['verify']);
      $manageModel = new manageModel;

      $map = [
        'manage_name' => $data['username'],
        'manage_pwd' => sha1(sha1($data['password'])),
        'manage_status'=>1
      ];

      if($manage=$manageModel->where($map)->find()){
        Session::set('TH_ID',$manage['id']);
        Session::set('TH_MANAGE_NAME',$data['username']);
        //登陆成功之后更新最后登录时间和IP地址
        $lastInfo = [
          'manage_lip'=>request()->ip(),
          'manage_ltime'=>TIME(),
        ];
        Db::name('manage')->where('id',$manage['id'])->update($lastInfo);
        $this->redirect('index/index','登录成功!');
      }else{
        $this->error('用户名或者密码错误!',url('login/index'));
      }
    }else{
      $this->error('非法登录!',url('login/index'));
    }

  }

  public function logout(){
        session(null);
        $this->redirect('index','退出成功！');
  }

//验证码是否正确
  public function check_verify($code){
    if(!captcha_check($code)){
      $this->error('验证码不正确!');
     }else{
       return true;
     }
  }
}
